<script setup lang="ts">
import { marked } from "marked";

interface Message {
  role: "user" | "assistant";
  content: string;
  loading?: boolean;
}

const messages = ref<Message[]>([]);
const inputMessage = ref("");
const isLoading = ref(false);

const API_URL = "https://api.deepseek.com/v1/chat/completions";
const API_KEY = "sk-08e543775a564a358483c29a6cdbf616";

async function sendMessage() {
  if (!inputMessage.value.trim() || isLoading.value) return;

  messages.value.push({
    role: "user",
    content: inputMessage.value
  });

  const aiMessage = ref({
    role: "assistant",
    content: "",
    loading: true
  }) as any;
  messages.value.push(aiMessage.value);

  isLoading.value = true;
  inputMessage.value = "";

  try {
    const response = await fetch(API_URL, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "Authorization": `Bearer ${API_KEY}`
      },
      body: JSON.stringify({
        model: "deepseek-chat",
        messages: messages.value
          .filter((m: Message) => !m.loading)
          .map(({ role, content }) => ({
            role,
            content
          })),
        stream: true,
        temperature: 0.7,
        max_tokens: 2000
      })
    });

    const reader = response.body?.getReader();
    const decoder = new TextDecoder();

    if (!reader) {
      throw new Error("获取响应流失败");
    }

    while (true) {
      const { done, value } = await reader.read();
      console.log(value);
      if (done) break;

      const chunk = decoder.decode(value);
      const lines = chunk.split("\n").filter((line: string) => line.trim());

      for (const line of lines) {
        if (line.startsWith("data: ")) {
          try {
            const data = JSON.parse(line.slice(5));
            if (data.choices?.[0]?.delta?.content) {
              aiMessage.value.content += data.choices[0].delta.content;
            }
          } catch (error) {
            console.error("解析响应数据失败:", error);
          }
        }
      }
    }
  } catch (error) {
    console.error("请求失败:", error);
    aiMessage.value.content = "抱歉，发生了错误，请稍后重试。";
  } finally {
    aiMessage.value.loading = false;
    isLoading.value = false;
  }
}

function handleKeydown(e: KeyboardEvent) {
  if (e.key === "Enter" && !e.shiftKey) {
    e.preventDefault();
    sendMessage();
  }
}
</script>

<template>
  <div class="chat-container">
    <div class="messages">
      <div
        v-for="(message, index) in messages"
        :key="index"
        class="message" :class="[message.role]"
      >
        <div class="avatar">
          {{ message.role === 'user' ? '👤' : '🤖' }}
        </div>
        <div class="content">
          <div class="text" v-html="marked(message.content)" />
          <div v-if="message.loading" class="typing">
            <span />
            <span />
            <span />
          </div>
        </div>
      </div>
    </div>

    <div class="input-area">
      <textarea
        v-model="inputMessage"
        :disabled="isLoading"
        placeholder="输入消息，Shift + Enter 换行，Enter 发送"
        @keydown="handleKeydown"
      />
      <button
        :disabled="isLoading || !inputMessage.trim()"
        @click="sendMessage"
      >
        <span v-if="isLoading" class="loading" />
        <span v-else>发送</span>
      </button>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.chat-container {
  height: calc(100vh - 220px);
  display: flex;
  flex-direction: column;
  background: #f5f5f5;
  padding: 20px;
}

.messages {
  flex: 1;
  overflow-y: auto;
  padding: 20px 0;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.message {
  display: flex;
  gap: 12px;
  max-width: 80%;

  &.user {
    align-self: flex-end;
    flex-direction: row-reverse;

    .content {
      background: #1890ff;
      color: white;
    }
  }

  &.assistant .content {
    background: white;
  }
}

.avatar {
  font-size: 24px;
  height: 40px;
  width: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.content {
  padding: 0px 10px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  min-width: 60px;
}

.text {
  word-break: break-word;
}

.typing {
  display: flex;
  gap: 4px;
  padding: 4px 0;

  span {
    width: 4px;
    height: 4px;
    background: currentColor;
    border-radius: 50%;
    animation: typing 1s infinite;
    opacity: 0.3;

    &:nth-child(2) {
      animation-delay: 0.2s;
    }
    &:nth-child(3) {
      animation-delay: 0.4s;
    }
  }
}

.input-area {
  margin-top: 20px;
  background: white;
  padding: 20px;
  border-radius: 8px;
  display: flex;
  gap: 12px;

  textarea {
    flex: 1;
    height: 80px;
    padding: 12px;
    border: 1px solid #d9d9d9;
    border-radius: 4px;
    resize: none;
    font-size: 14px;

    &:focus {
      outline: none;
      border-color: #1890ff;
    }

    &:disabled {
      background: #f5f5f5;
      cursor: not-allowed;
    }
  }

  button {
    padding: 0 24px;
    background: #1890ff;
    color: white;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    min-width: 80px;

    &:disabled {
      background: #d9d9d9;
      cursor: not-allowed;
    }
  }
}

.loading {
  width: 16px;
  height: 16px;
  border: 2px solid #ffffff;
  border-top-color: transparent;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes typing {
  0%,
  100% {
    transform: translateY(0);
  }
  50% {
    transform: translateY(-4px);
  }
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}
</style>
